import { Input, Tree } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import './style.less';

const { Search } = Input;

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const dataList = [];
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { key, title } = node;
    dataList.push({
      key,
      title,
    });
    if (node.children) {
      generateList(node.children);
    }
  }
};

const SearchableTree = (props) => {
  const { orgTreeData, ...restProps } = props;
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  generateList(orgTreeData);

  const onExpand = (newExpandedKeys) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const onChange = (e) => {
    const { value } = e.target;
    const newExpandedKeys = dataList
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, orgTreeData);
        }
        return null;
      })
      .filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  // 初始化--默认展开所有节点
  useEffect(() => {
    onChange({ target: { value: '' } });
  }, []);

  const showTreeData = useMemo(() => {
    const loop = (data) =>
      data.map((item) => {
        const strTitle = item.title;
        const index = strTitle.indexOf(searchValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return {
            ...item,
            title,
            key: item.key,
            children: loop(item.children),
          };
        }
        return {
          ...item,
          title,
          key: item.key,
        };
      });
    return loop(orgTreeData);
  }, [searchValue, orgTreeData]);

  return (
    <div style={{ padding: '8px 0' }}>
      <div style={{ padding: '0 12px' }}>
        <Search
          style={{
            marginBottom: 8,
          }}
          placeholder="请输入关键字查询"
          onChange={onChange}
        />
      </div>
      <div
        className="custom-scroll"
        style={{
          marginTop: '8px',
          padding: '0 12px 0 12px',
          height: '430px',
          overflowY: 'auto',
        }}
      >
        <Tree
          onExpand={onExpand}
          defaultExpandParent={true}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          treeData={showTreeData}
          {...restProps}
        />
      </div>
    </div>
  );
};
export default SearchableTree;
